import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
} from '@nestjs/common';
import { Response } from 'express';

@Catch(HttpException)
export class HttpExecptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status = exception.getStatus();
    const message = exception.message;

    const exceptionResponse = exception.getResponse();
    let validatorMessage = exceptionResponse;
    console.log(
      '🚀 ~ HttpExecptionFilter ~ catch ~ validatorMessage:',
      validatorMessage,
    );
    if (
      typeof validatorMessage === 'object' &&
      validatorMessage !== null &&
      'message' in validatorMessage
    ) {
      if (typeof validatorMessage.message === 'string') {
        validatorMessage = validatorMessage.message;
      } else {
        validatorMessage = validatorMessage.message?.[0] as string;
      }
    }

    response.status(status).json({
      code: status,
      message: validatorMessage || message,
    });
  }
}
